<template>
  <div class="custom-palette">
    <!-- 主工具栏 -->
    <div class="palette-toolbar">
      <!-- 基础工具 -->
      <div 
        class="toolbar-group"
        @click="activateTool('hand')"
        :class="{ active: activeTool === 'hand' }"
        title="移动工具">
        <i class="bpmn-icon-hand-tool"></i>
      </div>
      
      <div 
        class="toolbar-group"
        @click="activateTool('lasso')"
        :class="{ active: activeTool === 'lasso' }"
        title="选择工具">
        <i class="bpmn-icon-lasso-tool"></i>
      </div>
      
      <div 
        class="toolbar-group"
        @click="activateTool('global-connect')"
        :class="{ active: activeTool === 'global-connect' }"
        title="连线工具">
        <i class="bpmn-icon-connection-multi"></i>
      </div>
      
      <div class="toolbar-divider"></div>
      
      <!-- 事件分组 -->
      <div 
        class="toolbar-group"
        @mouseenter="showGroup('events', $event)"
        @mouseleave="hideGroup"
        :class="{ active: activeGroup === 'events' }"
        title="事件">
        <i class="bpmn-icon-start-event-none"></i>
      </div>
      
      <!-- 任务分组 -->
      <div 
        class="toolbar-group"
        @mouseenter="showGroup('tasks', $event)"
        @mouseleave="hideGroup"
        :class="{ active: activeGroup === 'tasks' }"
        title="任务">
        <i class="bpmn-icon-user-task"></i>
      </div>
      
      <!-- 网关分组 -->
      <div 
        class="toolbar-group"
        @mouseenter="showGroup('gateways', $event)"
        @mouseleave="hideGroup"
        :class="{ active: activeGroup === 'gateways' }"
        title="网关">
        <i class="bpmn-icon-gateway-xor"></i>
      </div>
      
      <!-- 其他分组 -->
      <div 
        class="toolbar-group"
        @mouseenter="showGroup('others', $event)"
        @mouseleave="hideGroup"
        :class="{ active: activeGroup === 'others' }"
        title="其他">
        <i class="bpmn-icon-subprocess-expanded"></i>
      </div>
    </div>
    
    <!-- 悬浮面板 -->
    <div 
      v-if="showFloatingPanel"
      class="floating-panel"
      :style="floatingPanelStyle"
      @mouseenter="keepPanelOpen"
      @mouseleave="hideGroup">
      
      <!-- 事件组件 -->
      <div v-if="activeGroup === 'events'" class="panel-content">
        <div class="panel-title">事件</div>
        <div class="panel-items">
          <div 
            class="panel-item"
            @mousedown="startDrag($event, 'bpmn:StartEvent')"
            title="开始事件">
            <i class="bpmn-icon-start-event-none"></i>
            <span>开始事件</span>
          </div>
          <div 
            class="panel-item"
            @mousedown="startDrag($event, 'bpmn:EndEvent')"
            title="结束事件">
            <i class="bpmn-icon-end-event-none"></i>
            <span>结束事件</span>
          </div>
          <div 
            class="panel-item"
            @mousedown="startDrag($event, 'bpmn:IntermediateThrowEvent')"
            title="中间事件">
            <i class="bpmn-icon-intermediate-event-none"></i>
            <span>中间事件</span>
          </div>
        </div>
      </div>
      
      <!-- 任务组件 -->
      <div v-if="activeGroup === 'tasks'" class="panel-content">
        <div class="panel-title">任务</div>
        <div class="panel-items">
          <div 
            class="panel-item"
            @mousedown="startDrag($event, 'bpmn:UserTask')"
            title="用户任务">
            <i class="bpmn-icon-user-task"></i>
            <span>用户任务</span>
          </div>
          <div 
            class="panel-item"
            @mousedown="startDrag($event, 'bpmn:ServiceTask')"
            title="服务任务">
            <i class="bpmn-icon-service-task"></i>
            <span>服务任务</span>
          </div>
          <div 
            class="panel-item"
            @mousedown="startDrag($event, 'bpmn:ScriptTask')"
            title="脚本任务">
            <i class="bpmn-icon-script-task"></i>
            <span>脚本任务</span>
          </div>
          <div 
            class="panel-item"
            @mousedown="startDrag($event, 'bpmn:BusinessRuleTask')"
            title="业务规则任务">
            <i class="bpmn-icon-business-rule-task"></i>
            <span>业务规则任务</span>
          </div>
          <div 
            class="panel-item"
            @mousedown="startDrag($event, 'bpmn:SendTask')"
            title="发送任务">
            <i class="bpmn-icon-send-task"></i>
            <span>发送任务</span>
          </div>
          <div 
            class="panel-item"
            @mousedown="startDrag($event, 'bpmn:ReceiveTask')"
            title="接收任务">
            <i class="bpmn-icon-receive-task"></i>
            <span>接收任务</span>
          </div>
          <div 
            class="panel-item"
            @mousedown="startDrag($event, 'bpmn:ManualTask')"
            title="手动任务">
            <i class="bpmn-icon-manual-task"></i>
            <span>手动任务</span>
          </div>
        </div>
      </div>
      
      <!-- 网关组件 -->
      <div v-if="activeGroup === 'gateways'" class="panel-content">
        <div class="panel-title">网关</div>
        <div class="panel-items">
          <div 
            class="panel-item"
            @mousedown="startDrag($event, 'bpmn:ExclusiveGateway')"
            title="排他网关">
            <i class="bpmn-icon-gateway-xor"></i>
            <span>排他网关</span>
          </div>
          <div 
            class="panel-item"
            @mousedown="startDrag($event, 'bpmn:ParallelGateway')"
            title="并行网关">
            <i class="bpmn-icon-gateway-parallel"></i>
            <span>并行网关</span>
          </div>
          <div 
            class="panel-item"
            @mousedown="startDrag($event, 'bpmn:InclusiveGateway')"
            title="包容网关">
            <i class="bpmn-icon-gateway-or"></i>
            <span>包容网关</span>
          </div>
          <div 
            class="panel-item"
            @mousedown="startDrag($event, 'bpmn:EventBasedGateway')"
            title="事件网关">
            <i class="bpmn-icon-gateway-eventbased"></i>
            <span>事件网关</span>
          </div>
        </div>
      </div>
      
      <!-- 其他组件 -->
      <div v-if="activeGroup === 'others'" class="panel-content">
        <div class="panel-title">其他</div>
        <div class="panel-items">
          <div 
            class="panel-item"
            @mousedown="startDrag($event, 'bpmn:SubProcess')"
            title="子流程">
            <i class="bpmn-icon-subprocess-expanded"></i>
            <span>子流程</span>
          </div>
          <div 
            class="panel-item"
            @mousedown="startDrag($event, 'bpmn:CallActivity')"
            title="调用活动">
            <i class="bpmn-icon-call-activity"></i>
            <span>调用活动</span>
          </div>
          <div 
            class="panel-item"
            @mousedown="startDrag($event, 'bpmn:DataStoreReference')"
            title="数据存储">
            <i class="bpmn-icon-data-store"></i>
            <span>数据存储</span>
          </div>
          <div 
            class="panel-item"
            @mousedown="startDrag($event, 'bpmn:DataObjectReference')"
            title="数据对象">
            <i class="bpmn-icon-data-object"></i>
            <span>数据对象</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted } from 'vue';
import BpmnModeler from 'bpmn-js/lib/Modeler';

interface Props {
  modeler: BpmnModeler;
}

const props = defineProps<Props>();
const activeTool = ref('');
const activeGroup = ref('');
const showFloatingPanel = ref(false);
const floatingPanelStyle = ref({});
const hoverTimer = ref<NodeJS.Timeout | null>(null);
const leaveTimer = ref<NodeJS.Timeout | null>(null);

// 激活工具
const activateTool = (toolType: string) => {
  if (!props.modeler) return;
  
  activeTool.value = toolType;
  
  try {
    switch (toolType) {
      case 'hand':
        const handTool = props.modeler.get('handTool') as any;
        handTool.activateHand();
        break;
      case 'lasso':
        const lassoTool = props.modeler.get('lassoTool') as any;
        lassoTool.activateSelection();
        break;
      case 'global-connect':
        const globalConnect = props.modeler.get('globalConnect') as any;
        globalConnect.toggle();
        break;
    }
  } catch (error) {
    console.error('激活工具失败:', error);
  }
};

// 显示分组面板
const showGroup = (groupName: string, event: MouseEvent) => {
  if (leaveTimer.value) {
    clearTimeout(leaveTimer.value);
    leaveTimer.value = null;
  }
  
  activeGroup.value = groupName;
  showFloatingPanel.value = true;
  
  // 计算悬浮面板位置
  const target = event.currentTarget as HTMLElement;
  const rect = target.getBoundingClientRect();
  
  floatingPanelStyle.value = {
    left: rect.right + 8 + 'px',
    top: rect.top + 'px'
  };
};

// 隐藏分组面板
const hideGroup = () => {
  leaveTimer.value = setTimeout(() => {
    showFloatingPanel.value = false;
    activeGroup.value = '';
  }, 100); // 100ms延迟，防止鼠标快速移动时闪烁
};

// 保持面板开启（鼠标移入悬浮面板时）
const keepPanelOpen = () => {
  if (leaveTimer.value) {
    clearTimeout(leaveTimer.value);
    leaveTimer.value = null;
  }
};

// 开始拖拽创建元素
const startDrag = (event: MouseEvent, elementType: string) => {
  if (!props.modeler) return;
  
  event.preventDefault();
  activeTool.value = '';
  
  try {
    const create = props.modeler.get('create') as any;
    const elementFactory = props.modeler.get('elementFactory') as any;
    
    let shape;
    
    if (elementType === 'bpmn:SubProcess') {
      // 子流程需要特殊处理
      const subProcess = elementFactory.createShape({
        type: 'bpmn:SubProcess',
        x: 0,
        y: 0,
        isExpanded: true
      });

      const startEvent = elementFactory.createShape({
        type: 'bpmn:StartEvent',
        x: 40,
        y: 82,
        parent: subProcess
      });

      create.start(event, [subProcess, startEvent], {
        hints: {
          autoSelect: [subProcess]
        }
      });
      return;
    } else {
      // 普通元素
      shape = elementFactory.createShape({
        type: elementType
      });
    }
    
    if (shape) {
      create.start(event, shape);
    }
  } catch (error) {
    console.error('创建元素失败:', error);
  }
};

onMounted(() => {
  // 监听选择变化，重置工具状态
  if (props.modeler) {
    const eventBus = props.modeler.get('eventBus') as any;
    eventBus.on('selection.changed', () => {
      activeTool.value = '';
    });
  }
});

// 组件销毁时清理定时器
const cleanup = () => {
  if (hoverTimer.value) {
    clearTimeout(hoverTimer.value);
  }
  if (leaveTimer.value) {
    clearTimeout(leaveTimer.value);
  }
};

// Vue 3 的 onUnmounted 生命周期钩子
onUnmounted(() => {
  cleanup();
});
</script>

<style lang="scss" scoped>
.custom-palette {
  position: absolute;
  left: 0;
  top: 0px;
  z-index: 100;
  user-select: none;
  
  .palette-toolbar {
    width: 44px; // 进一步减小宽度
    background: #ffffff;
    border: 1px solid #e5e7eb;
    border-radius: 0px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    padding: 4px 0; // 进一步减小内边距
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    
    .toolbar-group {
      width: 36px; // 进一步减小按钮区域
      height: 36px;
      margin: 1px 0; // 进一步减小间距
      border-radius: 6px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      transition: all 0.2s ease;
      position: relative;
      background: transparent;
      
      &:hover {
        background: #f3f4f6;
        transform: none; // 移除变形效果
        box-shadow: none;
      }
      
      &.active {
        i {
          color: #000000;
        }
      }
      
      i {
        font-size: 22px; // 保持图标大小
        color: #1f2937; // 使用更深的颜色，提高对比度
        transition: color 0.2s ease;
        font-weight: 600; // 增加字体粗细，让图标更清晰
      }
      
      &:hover i {
        color: #111827; // hover时使用更深的颜色
      }
    }
    
    .toolbar-divider {
      width: 20px; // 进一步减小分隔线宽度
      height: 1px;
      background: #e5e7eb;
      margin: 3px 0; // 进一步减小间距
    }
  }
  
  .floating-panel {
    position: fixed;
    background: #ffffff;
    border: 1px solid #e5e7eb;
    border-radius: 6px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
    z-index: 200;
    min-width: 120px; // 进一步减小最小宽度
    max-width: 220px;
    
    .panel-content {
      padding: 8px; // 进一步减小内边距
      
      .panel-title {
        font-size: 12px; // 进一步减小标题字体
        font-weight: 600;
        color: #374151;
        margin-bottom: 6px; // 进一步减小下边距
        padding-bottom: 6px;
        border-bottom: 1px solid #f3f4f6;
      }
      
      .panel-items {
        display: flex;
        flex-direction: column;
        gap: 2px; // 进一步减小间距
        
        .panel-item {
          display: flex;
          align-items: center;
          gap: 8px; // 减小图标与文字间距
          padding: 6px 8px; // 进一步减小内边距
          border-radius: 4px;
          cursor: pointer;
          transition: background 0.15s ease;
          
          &:hover {
            background: #f3f4f6;
            transform: none; // 移除位移效果
          }
          
          i {
            font-size: 18px; // 保持图标大小
            color: #1f2937; // 使用更深的颜色，提高对比度
            flex-shrink: 0;
            width: 18px;
            text-align: center;
            font-weight: 600; // 增加字体粗细
          }
          
          span {
            font-size: 12px; // 进一步减小文字
            color: #1f2937; // 使用更深的颜色提高可读性
            font-weight: 500;
            white-space: nowrap;
          }
          
          &:hover i {
            color: #111827; // hover时使用更深的颜色
          }
          
          &:hover span {
            color: #111827;
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .custom-palette {
    left: 0;
    top: 8px;
    
    .palette-toolbar {
      width: 56px;
      border-radius: 14px;
      padding: 10px 0;
      
      .toolbar-group {
        width: 40px;
        height: 40px;
        border-radius: 12px;
        
        i {
          font-size: 20px;
        }
      }
      
      .toolbar-divider {
        width: 32px;
      }
    }
    
    .floating-panel {
      min-width: 200px;
      max-width: 280px;
      border-radius: 14px;
      
      .panel-content {
        padding: 16px;
        
        .panel-title {
          font-size: 15px;
        }
        
        .panel-items {
          .panel-item {
            padding: 10px 14px;
            border-radius: 10px;
            
            i {
              font-size: 18px;
            }
            
            span {
              font-size: 14px;
            }
          }
        }
      }
    }
  }
}

// 滚动条优化
.floating-panel::-webkit-scrollbar {
  width: 6px;
}

.floating-panel::-webkit-scrollbar-track {
  background: rgba(241, 245, 249, 0.5);
  border-radius: 3px;
}

.floating-panel::-webkit-scrollbar-thumb {
  background: linear-gradient(to bottom, #cbd5e1, #94a3b8);
  border-radius: 3px;
  
  &:hover {
    background: linear-gradient(to bottom, #94a3b8, #64748b);
  }
}
</style>